"use strict";
/*
 * @Author: hongbin
 * @Date: 2023-01-27 17:17:04
 * @LastEditors: hongbin
 * @LastEditTime: 2023-03-05 11:18:01
 * @Description:键盘监听器
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyBoardListener = void 0;
var KeyBoardListener = /** @class */ (function () {
    function KeyBoardListener() {
        var _this = this;
        this.listenPool = {};
        this.handleDown = function (e) { return _this._handleDown.call(_this, e); };
        this.handleUp = function (e) { return _this._handleUp.call(_this, e); };
        if (KeyBoardListener.instance)
            return KeyBoardListener.instance;
        else
            KeyBoardListener.instance = this;
    }
    /**
     * 设置监听键和回调
     */
    KeyBoardListener.prototype.listenKey = function (key, press, raise) {
        this.listenPool[key] = { press: press, raise: raise, isPress: false };
        return this;
    };
    /**
     * 取消按键的监听
     */
    KeyBoardListener.prototype.cancelListenKey = function (key) {
        delete this.listenPool[key];
        return this;
    };
    /**
     * 执行按键的抬起事件
     */
    KeyBoardListener.prototype._callbackUp = function (key) {
        var keyConfig = this.listenPool[key];
        if (keyConfig) {
            keyConfig.isPress = false;
            keyConfig["raise"] && keyConfig["raise"]();
        }
    };
    /**
     * 执行按下的所有键对应的回调
     */
    KeyBoardListener.prototype._callbackDown = function (key) {
        var keyConfig = this.listenPool[key];
        if (!keyConfig)
            return;
        keyConfig.isPress = true;
        //所有按下未抬起的键均执行
        Object.values(this.listenPool).forEach(function (config) {
            if (config.isPress)
                config.press();
        });
    };
    KeyBoardListener.prototype._handleDown = function (e) {
        this._callbackDown(e.code);
    };
    KeyBoardListener.prototype._handleUp = function (e) {
        this._callbackUp(e.code);
    };
    /**
     * 开始监听键盘按键
     */
    KeyBoardListener.prototype.keyBoardListen = function () {
        document.addEventListener("keydown", this.handleDown);
        document.addEventListener("keyup", this.handleUp);
        return this;
    };
    /**
     * 移除键盘按键监听
     */
    KeyBoardListener.prototype.removeKeyBoardListen = function () {
        document.removeEventListener("keydown", this.handleDown);
        document.removeEventListener("keyup", this.handleUp);
    };
    return KeyBoardListener;
}());
exports.KeyBoardListener = KeyBoardListener;
